package controller;

import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import pojo.User;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController{
	@RequestMapping(value = "/list")
	@ResponseBody
	public String list() throws Exception {
		List<User> users = new ArrayList<User>();
		users.add(new User("admin", "admin", "ROLE_USER,ROLE_ADMIN"));
		users.add(new User("haha", "haha", "ROLE_USER"));
		users.add(new User("xixi", "xixi", "ROLE_USER"));
		
		ObjectMapper mapper = new ObjectMapper();
		Writer strWriter = new StringWriter();
		mapper.writeValue(strWriter, users);
		
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();  
		HttpServletRequest request = ((ServletRequestAttributes)ra).getRequest();
		String jsonpCallback = request.getParameter("jsonpCallback");
		
		if (jsonpCallback != null && !jsonpCallback.isEmpty()) {
			return jsonpCallback + "(" + strWriter.toString() + ")";
		} else {
			return strWriter.toString();
		}
		//return new JsonResult<List<User>>(users);
	}
}
